#!/bin/bash
#
# tomcat7     This shell script takes care of starting and stopping Tomcat
#
# chkconfig: - 80 20
#
### BEGIN INIT INFO
# Provides: tomcat7
# Required-Start: $network $syslog
# Required-Stop: $network $syslog
# Default-Start:
# Default-Stop:
# Description: Release implementation for Servlet 2.5 and JSP 2.1
# Short-Description: start and stop tomcat
### END INIT INFO

## Source function library.
#. /etc/rc.d/init.d/functions
JAVA_HOME=/etc/alternatives/jre
PATH=$JAVA_HOME/bin:$PATH
export PATH
TOMCAT_HOME=<%= scope.lookupvar('install_dir') %>/tomcat
SHUTDOWN_WAIT=20

tomcat_pid() {
  echo `ps aux | grep org.apache.catalina.startup.Bootstrap | grep -v grep | awk '{ print $2 }'`
}

start() {
  pid=$(tomcat_pid)
  if [ -n "$pid" ]
  then
    echo "Tomcat is already running (pid: $pid)"
  else
    echo "Starting tomcat"
    /bin/su tomcat $TOMCAT_HOME/bin/startup.sh
  fi

  return 0
}

stop() {
  pid=$(tomcat_pid)
  if [ -n "$pid" ]
  then
    echo "Stoping Tomcat"
    /bin/su -p -s /bin/sh tomcat $TOMCAT_HOME/bin/shutdown.sh

    let kwait=$SHUTDOWN_WAIT
    count=0;
    echo "Waiting $SHUTDOWN_WAIT seconds for processes to exit";
    until [ `ps -p $pid | grep -c $pid` = '0' ] || [ $count -gt $kwait ]
    do
      sleep 1
      echo -n '.'
      let count=$count+1;
    done
    echo

    if [ $count -gt $kwait ]; then
      echo "Killing processes $pid which didn't stop after $SHUTDOWN_WAIT seconds"
      kill -9 $pid
    fi
  else
    echo "Tomcat is not running"
  fi

  return 0
}

case $1 in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
  ;;
  status)
    pid=$(tomcat_pid)
    if [ -n "$pid" ]
      then
      echo "Tomcat is running with pid: $pid"
      exit 0
    else
      echo "Tomcat is not running"
      exit 3
    fi
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart|status}"
    exit 3
    ;;
esac
exit $?
